import logging

from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.index import index_blue
from info.models import User, News, Category
from info.utils.response_code import RET


@index_blue.route("/favicon.ico")
def title_favicon():
    # 发送图标到浏览器
    return current_app.send_static_file("news/favicon.ico")



@index_blue.route("/")
def index():
    # *获取当前用户信息
    # 获取到当前用户的id
    user_id = session.get("user_id")
    print("user_id = %s" %user_id)
    # 通过user_id获取到用户信息
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)


    # *获取新闻数据并按照点击量排行
    news = None
    try:
        # 获取查询排行榜热门新闻数据
        news = News.query.order_by(News.clicks.desc()).limit(constants.HOME_PAGE_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 将排行榜新闻数据按点击率遍历输出
    news_click_list = []
    for news_single in news:
        news_click_list.append(news_single.to_dict())


    # *新闻分类展示
    # 获取新闻分类数据
    categories = Category.query.all()
    # 定义保存分类列表
    categories_dicts = []
    for category in categories:
        categories_dicts.append(category.to_dict())



    data = {"user_info": user.to_dict() if user else None,
            "click_news_list": news_click_list,
            "categories": categories_dicts
            }

    return render_template("news/index.html", data=data)



@index_blue.route("/news_list")
def news_list():
    """
    新闻列表数据
    :return:
    """

    # 获取参数
    # 分类id, 第二个参数表示从1开始
    cid = request.args.get("cid", "1")
    # 表示第几个页面,第二个参数表示从第一页开始
    page = request.args.get("page", "1")
    # 表示每个页面的数据个数
    per_page = request.args.get("per_page", constants.OTHER_NEWS_PAGE_MAX_COUNT)

    # 校验参数
    try:
        # 穿进来的值为字符串,需改成int型
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        cid = 1
        page = 1
        per_page = 10

    # 查询数据
    # if cid == 1:
    #     paginate = News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    # else:
    #     paginate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page, per_page, False)

    filters = []
    # cid==1时,显示所有类的最新数据(最新类), cid!=1时,按照其他分类的时间顺序
    if cid != 1:
        filters.append(News.category_id == cid)
    # 获取新闻数据
    # 分页函数:paginate(page表示页数, per_page每页显示数据, 是否输出错误errout)
    paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    # 查询到的数据
    items = paginate.items
    # 当前页面
    current_page = paginate.page
    # 总条目数
    total_page = paginate.pages

    news_list = []
    for item in items:
        news_list.append(item.to_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_dict_li": news_list
    }
# 返回数据
    return jsonify(errno = RET.OK, errmsg = "OK", data=data)